package com.yylending.las.lending;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.widgets.RedDotView;
import com.yylending.las.common.widgets.TelephoneTextView;
import com.yylending.las.lending.process.IncreaseLimitByPolicyActivity;
import com.yylending.las.lending.process.PreIncreaseLimitActivity;
import com.yylending.las.lending.process.ProcessActivity;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.lending.quota.myquota.MyQuotaPresenter;
import com.yylending.las.main.MainController;
import com.yylending.las.personal.bandcard.BankCardActivity;
import com.yylending.las.personal.bandcard.BankCardModel;
import com.yylending.las.personal.bandcard.BankCardPresenter;
import com.yylending.las.personal.bandcard.BoundBankCards;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 借钱页面-有额度
 * Created by laixj on 2017/5/22.
 * Copyright ©2017 www.yylending.com. All Rights Reserved.
 */
public class HaveQuotaFragment extends BaseFragment implements BankCardPresenter.View {
    static final String TAG = HaveQuotaFragment.class.getSimpleName();

    static final int LOADER_ID_MY_QUOTA = -111;
    static final String ARG_APPLY_STATUS = "arg_apply_status";

    Unbinder unbinder;
    @BindView(R.id.title_left_iv)
    ImageView mTitleLeftIv;
    @BindView(R.id.title_tv)
    TextView mTitleTv;
    @BindView(R.id.title_right_tv)
    TextView mTitleRightTv;
    @BindView(R.id.title_right_iv)
    ImageView mTitleRightIv;
    @BindView(R.id.layout_title_bar)
    RelativeLayout mLayoutTitleBar;
    @BindView(R.id.text_my_limit)
    TextView mTextMyLimit;
    @BindView(R.id.limit_sum_tv)
    TextView mLimitSumTv;
    @BindView(R.id.increase_limit_tv)
    TextView mIncreaseLimitTv;
    @BindView(R.id.loan_btn)
    Button mLoanBtn;
    @BindView(R.id.lending_notice_tv)
    TextView mLendingNoticeTv;
    @BindView(R.id.service_phone_tv)
    TelephoneTextView mServicePhoneTv;
    @BindView(R.id.red_dot_view)
    RedDotView mRedDotView;

    /**
     * 额度状态
     */
    private MyQuotaModel.ApplyStatus mApplyStatus;
    /**
     * 我的额度值
     */
    private String mQuota = "0";
    private BankCardPresenter mBankCardPresenter;

    public static BaseFragment newInstance(MyQuotaModel.ApplyStatus status) {
        BaseFragment fragment = new HaveQuotaFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_APPLY_STATUS, status);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mApplyStatus = bundle.getParcelable(ARG_APPLY_STATUS);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.view_stub_have_limit, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    private void initView() {
        mLayoutTitleBar.setBackgroundResource(0);
		mLayoutTitleBar.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.transparent));
		mTitleTv.setText(R.string.tab_lend);
		mTitleLeftIv.setImageResource(R.drawable.ic_help_black);
		mTitleRightIv.setImageResource(R.drawable.ic_message_black);
        mServicePhoneTv.setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);
        if (null != mApplyStatus && Constants.PROMOTE_STATUS_HAVE.equals(mApplyStatus.promoteAmount)) {
            mIncreaseLimitTv.setVisibility(View.VISIBLE);
        } else {
            mIncreaseLimitTv.setVisibility(View.GONE);
        }
        if (null != mApplyStatus) {
            mQuota = mApplyStatus.quota.ts;
        }
        mLimitSumTv.setText(FormatUtils.getDecoratedAmountWithSymbol(mQuota));
        getActivity().getSupportLoaderManager().initLoader(LOADER_ID_MY_QUOTA, null, this);
        MainController.initRedDot(mRedDotView);
    }

    @Override
    public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
        switch (loader.getId()) {
            case LOADER_ID_MY_QUOTA:
                mBankCardPresenter = (BankCardPresenter) data;
                mBankCardPresenter.attach(this);
                break;
        }
    }

    @Override
    public Loader<Presenter> onCreateLoader(int id, Bundle args) {
        switch (id) {
            case LOADER_ID_MY_QUOTA:
                return new PresenterLoader<>(getActivity(), new BankCardPresenter.Generator());
            default:
                return null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_MY_QUOTA);
    }

    @OnClick({R.id.increase_limit_tv, R.id.loan_btn, R.id.lending_notice_tv, R.id.title_left_iv, R.id.title_right_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_iv:
                EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_HELP_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
                break;
            case R.id.title_right_iv:
                EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_MESSAGE_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
                MainController.hideRedDot(mRedDotView);
                break;
            case R.id.increase_limit_tv:
                //StatService.onEvent(getContext(), StatIDSet.EVENT_ID_INCREASE_LOAN_ENTRANCE);
				PreIncreaseLimitActivity.start(getActivity());
                break;
            case R.id.loan_btn:
                showLoading(false);
                mBankCardPresenter.getMyBankCard(true);
                break;
            case R.id.lending_notice_tv:
                EventAgent.post(new QuotaEvent.ShowLoanNoticeEvent(QuotaEvent.ShowLoanNoticeEvent.QUOTA_SHOW_LOAN_NOTICE, Constants.PAGE_NO_MAIN_ACTIVITY));
                break;
        }
    }

    @Override
    public void bindCardSuccess() {
    }

    @Override
    public void bindCardFailed(String msg) {
    }

    @Override
    public void hasBindBankCard(boolean isManual, List<BoundBankCards.BankInfo> bankInfo) {
		HashMap<String, String> map = new HashMap<>();
		map.put(StatService.ATTRIBUTE_KEY_ONE, StatService.ATTRIBUTE_VALUE_ONE);
		if(MyQuotaPresenter.largeThanMaxOnlineQuota(mApplyStatus)){
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_ONE);
		}else{
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_TWO);
		}
		StatService.onEvent(getContext(), StatIDSet.EVENT_ID_BEGIN_BORROW_MONEY, map);
		ProcessActivity.start(getActivity(), mApplyStatus, bankInfo);
    }

    @Override
    public void neverBindBankCard(boolean isManual) {
		HashMap<String, String> map = new HashMap<>();
		map.put(StatService.ATTRIBUTE_KEY_ONE, StatService.ATTRIBUTE_VALUE_TWO);
		if(MyQuotaPresenter.largeThanMaxOnlineQuota(mApplyStatus)){
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_ONE);
		}else{
			map.put(StatService.ATTRIBUTE_KEY_TWO, StatService.ATTRIBUTE_VALUE_TWO);
		}
		StatService.onEvent(getContext(), StatIDSet.EVENT_ID_BEGIN_BORROW_MONEY, map);
        BankCardActivity.start(getActivity(), null, mApplyStatus, Constants.KEY_GOTO_BIND_CARD_FROM_HAVE_QUOTA_FRAGMENT);
    }

    @Override
    public void requestBindBankCardFailed(boolean isManual) {
    }

    @Override
    public void getSupportBankSuccess(List<BankCardModel.SupportBankList.SupportBank> supportBankList) {
    }

    @Override
    public void getSupportBankFailed(String msg) {
    }

    @Override
    public void bindCardRetCode(String retCode) {

    }

    @Override
    public void onFunctionalCompleted(boolean autoTips) {
        super.onFunctionalCompleted(autoTips);
        dismissLoading();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRedDotShowEvent(QuotaEvent.ShowRedDotEvent event) {
        mRedDotView.setVisibility(View.VISIBLE);
    }
}